<template>
    <div class="app-container" v-loading="listLoading">
        <el-form ref="form" label-width="80px">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="设备名称">
                        <el-input v-model="queryParms.name"></el-input>
                    </el-form-item>
                </el-col>
             
                <el-col :span="14">
                    <el-button type="primary" @click="queryPage">搜索</el-button>
                    <el-button type="success" @click="showAddDialog" v-if="role==1">新增</el-button>
                </el-col>

                <el-col :span="4">
                    <el-select v-model="app_id" placeholder="选择项目">
                        <el-option
                        v-for="item in projectList"
                        :key="item.app_id"
                        :label="item.name"
                        :value="item.app_id">
                        </el-option>
                    </el-select>
                </el-col>
               
            </el-row>

        </el-form>
       

        <el-table  :data="list" element-loading-text="Loading" border fit highlight-current-row>
            <el-table-column  label="设备名称" width="300px">
                <template slot-scope="scope">
                    {{ scope.row.name }}
                </template>
            </el-table-column>
            <el-table-column label="设备key" width="200px">
                <template slot-scope="scope">
                    {{ scope.row.device_bd_key }}
                </template>
            </el-table-column>
            <el-table-column label="数据单位" width="200px">
                <template slot-scope="scope">
                    {{ scope.row.unit }}
                </template>
            </el-table-column>
            <el-table-column label="设备类型" width="200px">
                <template slot-scope="scope">
                    {{ getDviceTypeName(scope.row.device_type)  }}
                </template>
            </el-table-column>
            <el-table-column label="在线状态" width="150px">
                <template slot-scope="scope">
                    <span v-if="scope.row.is_line" style="color: #37F67D">在线</span>
                    <span v-else style="color: #FFB325;">离线</span>
          
                </template>
            </el-table-column>
            <el-table-column label="最后在线时间" width="300px">
                <template slot-scope="scope">
                    <span>{{getTime(scope.row.last_line_time)}}</span>
                </template>
            </el-table-column>

            <el-table-column label="报警类型" width="150px">
                <template slot-scope="scope">
                    <span v-if="scope.row.last_warning_id" :style="{color:scope.row.last_warning_type=='yellow'?'#ffd600':scope.row.last_warning_type}">{{colorList[scope.row.last_warning_type]}}报警</span>
                    <span v-else>无</span>
                </template>
            </el-table-column>

            <el-table-column label="最后数据">
                <template slot-scope="scope">
                    <span>{{getDataList(scope.row.last_real_value)}}</span>
                </template>
            </el-table-column>
           
          
           
            <el-table-column  label="操作" width="250">
                <template slot-scope="scope">
                    <el-button type="text" @click="showDrawer(scope.row)" v-if="role==1">位置信息</el-button>

                    <el-button type="text" @click="showDanger(scope.row)">报警设置</el-button>

                    <el-button type="text" @click="showEditDialog(scope.row)" v-if="role==1">编辑</el-button>
                    <el-button type="text" @click="deleteItem(scope.row)" v-if="role==1">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
            style="float: right;margin-top: 20px;"
            @current-change="changePage"
            background
            layout="prev, pager, next,jumper"
            :total="queryParms.total">
        </el-pagination>


        <el-dialog title="新增设备" :visible.sync="dialogFormVisible">
            <el-form :model="form">
                <el-form-item label="设备名称" :label-width="formLabelWidth">
                    <el-input v-model="form.name" autocomplete="off" placeholder="请输入设备名称"></el-input>
                </el-form-item>
                <el-form-item label="设备key" :label-width="formLabelWidth">
                    <el-input v-model="form.device_bd_key" autocomplete="off" placeholder="请输入设备key"></el-input>
                </el-form-item>
                <el-form-item label="数据单位" :label-width="formLabelWidth">
                    <el-input v-model="form.unit" autocomplete="off" placeholder="请输入数据单位"></el-input>
                </el-form-item>
                <el-form-item label="设备类型" :label-width="formLabelWidth">
                    <el-select v-model="form.device_type" placeholder="请选择">
                        <el-option
                        v-for="item in deviceTypeList"
                        :key="item.keyword"
                        :label="item.name"
                        :value="item.keyword">
                        </el-option>
                    </el-select>

                </el-form-item>
           
                <el-form-item label="设备照片" :label-width="formLabelWidth">
                    <!-- <div class="upload_div">
                        <i class="el-icon-plus"></i>
                    </div> -->

                    <div class="imgMainDiv" v-if="form.face_img_list.length>0">
                        <template v-for="(item,index) in form.face_img_list">
                            <div class="img_div" style="width: 160px; height: 160px">
                                <el-image 
                                    style="width: 160px; height: 160px"
                                    :src="item" 
                                    :preview-src-list="form.face_img_list">
                                </el-image>
                                <i class="el-icon-error" @click="deleteImg(index,1,'face_img_list')"></i>
                            </div>
                            
                        </template>
                       
                        <!-- <img :src="form.face_img"> -->
                    </div>
                    <div class="upload_div">
                        <i class="el-icon-plus"></i>
                        <input type="file" accept="image/*" @change="changeFile($event,'face_img_list',1)"/>
                    </div>
                </el-form-item>
               
         
               
                <el-form-item label="设备简介" :label-width="formLabelWidth">
                    <el-input
                        type="textarea"
                        :rows="5"
                        resize="none"
                        placeholder="请输入内容"
                        v-model="form.intro">
                    </el-input>
                    <!-- <el-input v-model="form.intro" autocomplete="off" placeholder="请输入项目简介"></el-input> -->
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="sureForm">确 定</el-button>
            </div>
        </el-dialog>


        <el-drawer
            title="报警设置"
            :visible.sync="drawer"
            size="50%"
            direction="rtl">
            <div class="positondiv">
                
            
                <el-form ref="form" label-width="80px">
                   
                    <el-row :gutter="20">
                        <el-col :span="14">
                            <el-button type="success" style="margin-bottom: 20px;" v-if="role==1" @click="showAddWarningDialog">新增</el-button>
                        </el-col>
                    </el-row>

                </el-form>
        
                <el-table  :data="warningList" element-loading-text="Loading" border fit highlight-current-row>
                    <el-table-column  label="报警类型">
                        <template slot-scope="scope">
                            {{ wanrgingType[scope.row.warning_type] }}
                        </template>
                    </el-table-column>
                    <el-table-column label="报警值" >
                        <template slot-scope="scope">
                            {{ scope.row.warning_value }}
                        </template>
                    </el-table-column>
                    <el-table-column label="报警次数">
                        <template slot-scope="scope">
                            {{ scope.row.warning_num }}
                        </template>
                    </el-table-column>

                    <el-table-column label="是否屏蔽">
                        <template slot-scope="scope">
                            <span v-if="scope.row.is_stop" style="color: #FFB325;">屏蔽</span>
                            <span v-else style="color: #37F67D;">未屏蔽</span>
                   
                        </template>
                    </el-table-column>
                
                
                
              
                </el-table>
            </div>
        </el-drawer>





        <el-dialog title="位置信息" :visible.sync="dialogPositionFormVisible">
            <el-form :model="posititonForm">

                <el-form-item label="点选位置" :label-width="formLabelWidth">
                    <div class="mapmain" v-if="!gps_info.face_img">
                        <div id="container"></div>
                        <div class="search_input">
                            <input id="tipinput" placeholder="请输入关键字搜索"/>
                        </div>
                    </div>
                    <div class="mapmain" v-else>
                        <div class="face_img_main" @click="addPoint">
                            <img :src="gps_info.face_img">

                            <div class="poiont_div"  v-if="posititonForm.face_img_coordinate">
                                <img src="//webapi.amap.com/theme/v1.3/markers/b/mark_bs.png">
                            </div>
                        </div>
                    </div>
                   
                </el-form-item>
               
             
               
       
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogPositionFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="surePostionForm">确 定</el-button>
            </div>
        </el-dialog>



        <el-dialog title="报警设置" :visible.sync="dialogWarningFormVisible">
            <el-form :model="wanrgingForm">

                <el-form-item label="报警类型" :label-width="formLabelWidth">
                
                    <el-select v-model="wanrgingForm.warning_type" placeholder="请选择">
                        <el-option
                        v-for="item in wanrgingTypeList"
                        :key="item.key"
                        :label="item.name"
                        :value="item.key">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="报警值" :label-width="formLabelWidth">
                    <el-input v-model="wanrgingForm.warning_value" placeholder="请输入报警值"></el-input>
               
                </el-form-item>

                <el-form-item label="时间限制" :label-width="formLabelWidth" v-if="wanrgingForm.device_type=='rain_gauge'">
                   
                    <el-select v-model="wanrgingForm.time_limit" placeholder="时间限制">
                        <el-option
                        v-for="item in time_limit_list"
                        :key="item.key"
                        :label="item.name"
                        :value="item.key">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="是否屏蔽" :label-width="formLabelWidth" v-if="wanrgingForm.device_type=='rain_gauge'">
                   
                    <el-radio-group v-model="wanrgingForm.is_stop">
                        <el-radio :label="1">屏蔽</el-radio>
                        <el-radio :label="0">不屏蔽</el-radio>
                   
                    </el-radio-group>
               </el-form-item>
               
       
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogWarningFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="sureWarningForm">确 定</el-button>
            </div>
        </el-dialog>



        
    </div>
</template>

<script>
import homeapi from '@/api/tailings_monitoring_service_smos_api.js'
import until from '@/api/until.js'
import { mapGetters } from 'vuex'
export default {
    data() {
        return {
            list: null,
            listLoading: true,
            queryParms:{
                page:1,
                page_size:10,
                name:"",
                total:0,
               
            },
            form:{
                app_id:"",
                name:"",
                device_bd_key:"",
                intro:"",
                device_type:"",
                unit:"",
                photo:"",
                face_img_list:[],
            },
            dialogFormVisible:false,
            formLabelWidth:'100px',
            projectList:[],
            app_id:"",
            deviceTypeList:[],

            drawer:false,
            nowItem:{},

            devicePositionList:[],
            posititonForm:{
                app_id:"",
                device_id:"",
                gps_lng:"",
                gps_lat:"",
                face_img_coordinate:"",
            },

            dialogPositionFormVisible:false,
            map:null,
            maker:null,
            colorList:{
                'yellow':'黄色',
                'red':"红色",
                'blue':"蓝色",
                'orange':'橙色'
            },
            gps_info:"",
            warningList:[],
            dialogWarningFormVisible:false,
            wanrgingForm:{
                app_id:"",
                device_id:"",
                device_type:"",
                warning_type:"",
                warning_value:"",
                time_limit:"",
                is_stop:0,
            },

            wanrgingTypeList:[
                {
                    key:"blue",
                    name:"蓝色报警",
                },
                {
                    key:"yellow",
                    name:"黄色报警",
                },
                {
                    key:"orange",
                    name:"橙色报警",
                },
                {
                    key:"red",
                    name:"红色报塾",
                }
            ],
            wanrgingType:{
                blue:"蓝色报警",
                yellow:"黄色报警",
                orange:"橙色报警",
                red:"红色报塾"
            },
            time_limit_list:[
                {
                    key:"3",
                    name:"3小时"
                },
                {
                    key:"6",
                    name:"6小时"
                },
                {
                    key:"9",
                    name:"9小时"
                },
                {
                    key:"12",
                    name:"12小时"
                },
                {
                    key:"15",
                    name:"15小时"
                },
                {
                    key:"18",
                    name:"18小时"
                },
                {
                    key:"21",
                    name:"21小时"
                },
                {
                    key:"24",
                    name:"24小时"
                },
            ]
        }
    },
    watch:{
        app_id(){
            until.setCookie("app_id",this.app_id)
            this.getDeviceList();
        }
    },
    computed: {
        ...mapGetters([
        'role',
        
        ])
    },
    created() {
        

        this.fetchData()
        this.getDeviceType();
    },
    methods: {
   

        deleteImg(index,isArry,type){
            if(isArry){
                if(this.dialogFormVisible){
                    this.form[type].splice(index,1)
                }
                else{
                    this.posititonForm[type].splice(index,1);
                }
                
            }
            else{
                if(this.dialogFormVisible){
                    this.form[type]=""
                }
                else{
                    this.posititonForm[type]=""
                }
            }
        },
        changePage(page){
            this.queryParms.page=page;
            this.getDeviceList();
        },

        async sureWarningForm(){
            let form=this.wanrgingForm;
        
            let data=await homeapi.Smos_apiDevice_warningCreatePost(form);
            if(data.error_code==0){
                this.dialogWarningFormVisible=false;
                this.getWarningList();
            }
        },

        showDanger(item){
            this.drawer=true;
            this.nowItem=item
            this.getWarningList();
        },
        //获取报警列表
        async getWarningList(){
            let app_id=this.app_id
            let device_id=this.nowItem.device_id
            let data=await homeapi.Smos_apiDevice_warningAllGet({app_id,device_id});
            if(data.error_code==0){
                this.warningList=data.data.list
            }


        },
        showAddWarningDialog(){
            this.dialogWarningFormVisible=true;
            this.wanrgingForm={
                app_id:this.app_id,
                device_id:this.nowItem.device_id,
                device_type:this.nowItem.device_type,
                warning_type:"",
                warning_value:"",
                time_limit:"",
                is_stop:0,
            }
        },

        getDataList(dataList){
            let dataName=""
            dataList.map(res=>{
                if(dataName==""){
                    dataName=res.value_name+":"+res.value+res.value_unit
                }
                else{
                    dataName+=","+res.value_name+":"+res.value+res.value_unit
                }
            })
            return dataName
        },

        getTime(time){
            return until.formatDateChinese(time*1000)
        },

        async getDeviceType(){
            let data=await homeapi.Smos_apiDeviceTypesGet();
            if(data.error_code==0){
                this.deviceTypeList=data.data;
            }
        },
        getDviceTypeName(device_type){
            let name=""
            this.deviceTypeList.map(res=>{
                if(res.keyword==device_type){
                    name=res.name;
                }
            })
            return name;
        },
        async fetchData() {
            let form=this.queryParms
            let data=await homeapi.Smos_apiAppPageGet(form);
            if(data.error_code==0){
                this.listLoading=false;
                this.projectList=data.data.list;
                this.$nextTick(()=>{
                    let app_id=until.getCookie("app_id");
                    if(app_id){
                        this.app_id=parseInt(app_id) 

                    }
                    else{
                        this.app_id=data.data.list[0].app_id;
                    }
                    this.getAppInfo();
             

              
                })
            }
        },
        //获取在线统计
		async getAppInfo(){
			let app_id=this.app_id
			let data=await homeapi.Smos_apiAppDetailGet({app_id});
			if(data.error_code==0){

				this.gps_info=data.data;
			}
		},

        queryPage(){
            this.queryParms.page=1;
            this.getDeviceList();
        },
        showAddDialog(){
            this.dialogFormVisible=true;
            this.form={
                app_id:"",
                name:"",
                device_bd_key:"",
                intro:"",
                device_type:"",
                unit:"",
                photo:"",
                face_img_list:[],
            }
        },
        async sureForm(){
            if(this.form.device_id){
                this.editForm();
            }
            else{
                this.addForm();
            }
        },
        async getDeviceList(){
            let form=this.queryParms;
            form.app_id=this.app_id;
            let data=await homeapi.Smos_apiDevicePageGet(form);
            if(data.error_code==0){
                this.list=data.data.list?data.data.list:[];
                this.queryParms.total=data.data.total
            }
        },
        async addForm(){
            let form=this.form;
            form.app_id=this.app_id;
            form.photo=form.face_img_list.length>0?form.face_img_list.length.join(","):""
            this.listLoading=true;
            let data=await homeapi.Smos_apiDeviceCreatePost(form);
            console.log(data)
            if(data.error_code==0){
                this.listLoading=false
                this.$message.success("新增成功")
                this.dialogFormVisible=false;
                this.getDeviceList();

            }
        },
        async editForm(){
            let form=this.form;
            form.app_id=this.app_id;
             form.photo=form.face_img_list.length>0?form.face_img_list.length.join(","):""
            this.listLoading=true;
            let data=await homeapi.Smos_apiDeviceUpgradePut(form);
            if(data.error_code==0){
                this.listLoading=false
                this.$message.success("编辑成功")
                this.dialogFormVisible=false;
                this.getDeviceList();

            }
        },
        showEditDialog(item){
            this.dialogFormVisible=true;
            item.face_img_list=item.photo?item.photo.split(","):[]
            this.form=item;
        },
        async changeFile(e,type,isArry){
            
            let file=e.target.files[0];
            var formData = new FormData();
            // 服务端要求参数是 pic1 
            formData.append('image',file);
            console.log(formData)
            this.listLoading=true;
            let data=await homeapi.Smos_apiUpload_imgPost({},formData);
            if(data.error_code==0){
                this.listLoading=false
                if(this.dialogFormVisible){
                    if(isArry){
                        this.form[type].push(data.data)
                    }
                    else{
                        this.form[type]=data.data
                    }
                   
                }
                else{
                    if(isArry){
                        this.posititonForm[type].push(data.data)
                    }
                    else{   
                        this.posititonForm[type]=data.data
                    }   
                   
                }
                
            }
        },
        async deleteItem(item){
            this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
             }).then(async () => {
                let app_id=item.app_id
                let device_id=item.device_id
                this.listLoading=true;
                let data=await homeapi.Smos_apiDeviceDeleteDelete({app_id,device_id});
                if(data.error_code==0){
                    this.listLoading=false;
                    this.$message.success("删除成功");
                    this.getDeviceList();
                }
            }).catch(() => {
            });
        },
        showDrawer(item){
            // this.drawer=true
            this.nowItem=item;
            this.getDevicePositionList();
        },
        //获取设备位置信息
        async getDevicePositionList(){
            let app_id=this.app_id
            let device_id=this.nowItem.device_id
            let data=await homeapi.Smos_apiDevice_addressAllGet({app_id,device_id});
            if(data.error_code==0){
                this.devicePositionList=data.data.list;
                this.showAddPositionDialog();
            }
        },
        showAddPositionDialog(){
            let gps_lng=""
            let gps_lat=""
            if(this.devicePositionList.length>0){
                gps_lng=this.devicePositionList[0].gps_lng
                gps_lat=this.devicePositionList[0].gps_lat
            }
            this.posititonForm={
                app_id:this.app_id,
                device_id:this.nowItem.device_id,
                gps_lng:gps_lng,
                gps_lat:gps_lat,
                face_img_coordinate:this.nowItem.address_info.face_img_coordinate,
            }
            try{
                let face_img_coordinate=this.nowItem.address_info.face_img_coordinate?JSON.parse(this.nowItem.address_info.face_img_coordinate):{}
                this.$nextTick(()=>{
                    if(face_img_coordinate.imgX){
                        document.querySelector(".poiont_div").style.left=(face_img_coordinate.imgX-9)+'px'
                        document.querySelector(".poiont_div").style.top=(face_img_coordinate.imgY-16)+'px'
                    }
                
                })
            }
            catch{
                this.posititonForm.face_img_coordinate=""
            }
           
            this.dialogPositionFormVisible=true;
            if(!this.gps_info.face_img){
                this.$nextTick(()=>{
                    this.createMap();
                })
            }
           
        },
        createMap(){
            let _this=this;
            window.AMapLoader.load({
                key: "4dcf7ff87677856989b63e34501cc00e", //申请好的Web端开发者 Key，调用 load 时必填
                version: "2.0", //指定要加载的 JS API 的版本，缺省时默认为 1.4.15
            }).then((AMap) => {
                
                this.map = new AMap.Map("container",{
                    center: [102.80, 25.004],
                    zoom:16,
                    layers:[
                        new AMap.TileLayer.RoadNet({
                            zIndex:25
                        }),
                        new AMap.TileLayer.Satellite()
                    ]
                });
                this.map.on("click", this.clickListener);
                var autoOptions = {
                    input: "tipinput"
                };
                if(this.posititonForm.gps_lat && this.posititonForm.gps_lng){
                    this.maker=new AMap.Marker({
                        position: [this.posititonForm.gps_lng,this.posititonForm.gps_lat],
                        map: this.map
                    });
                }
                AMap.plugin(['AMap.PlaceSearch','AMap.AutoComplete'], function(){
                    var auto = new AMap.AutoComplete(autoOptions);
                    console.log(auto)
                    var placeSearch = new AMap.PlaceSearch({
                        map: _this.map
                    });  //构造地点查询类
                    auto.on("select", select);//注册监听，当选中某条记录时会触发
                    function select(e) {
                        console.log(e)
                        placeSearch.setCity(e.poi.adcode);
                        placeSearch.search(e.poi.name);  //关键字查询查询
                    }
                });
                if(_this.gps_info.gps_info){
                    let gps_info=JSON.parse(_this.gps_info.gps_info);
                    var polygonMain = new AMap.Polygon({
                        map: _this.map,
                        path: gps_info, // 多边形的点
                        strokeColor: "#FF33FF", 
                        strokeOpacity: 1,
                        strokeWeight: 6,
                        strokeOpacity: 0.2,
                        fillColor: '#1791fc',
                        fillOpacity: 0.4,
                        // 线样式还支持 'dashed'
                        strokeStyle: "solid",
                    });
                    var bounds = polygonMain.getBounds()
                    console.log(bounds)
                 
                    var center = bounds.getCenter();
                    _this.map.setCenter(center); 
                    polygonMain.on("click", this.clickListener);
                }
            })
            .catch((e) => {
                console.error(e); //加载错误提示
            });
        },
        clickListener(e){
            if(this.maker){
                this.maker.setMap(null);
                this.maker = null;
            }
            this.maker=new AMap.Marker({
                position: e.lnglat,
                map: this.map
            });

            this.posititonForm.gps_lng=e.lnglat.lng
            this.posititonForm.gps_lat=e.lnglat.lat
        },
        async surePostionForm(){
            let form=this.posititonForm;
            this.listLoading=true;
            let data=await homeapi.Smos_apiDevice_addressCreatePost(form)
            if(data.error_code==0){
                this.listLoading=false;
                this.$message.success("新增成功");
                this.dialogPositionFormVisible=false;
            }
           
        },
        addPoint(e){
            let face_img_coordinate={
                imgX:e.offsetX,
                imgY:e.offsetY
            }
            this.posititonForm.face_img_coordinate=JSON.stringify(face_img_coordinate)
            this.$nextTick(()=>{
                console.log(document.querySelector(".poiont_div"))
                document.querySelector(".poiont_div").style.left=(e.offsetX-9)+'px'
                document.querySelector(".poiont_div").style.top=(e.offsetY-16)+'px'
            })
         
        }
    }
}
</script>
<style lang="css" scoped>
    .upload_div{
        width: 160px;
        height: 160px;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 1px solid #ddd;
        border-radius: 8px;
        position: relative;
        float: left;
        margin-left: 10px;
        

    }
    .upload_div input{
        position: absolute;
        top: 0;
        left: 0;
        opacity: 0;
        width: 100%;
        height: 100%;
    }
    .imgdiv{
        width: 120px;
        
    }
    .imgdiv img{
        width: 100%;
       
    }
    .upload_div i{
        font-size: 32px;
    }
    .imgMainDiv{
       display: flex;
       align-items: center;
       justify-content: flex-start;
       float: left;
    }
    .imgMainDiv img{
        width: 100%;
        height: 100%;
    }
    .img_div{
        position: relative;
    }
    .img_div i{
        position: absolute;
        top: 5px;
        right: 5px;
        color: #F56C6C;
    }
    .face_img_main{
        width: 500px;
        height: 500px;
        position: relative;
    }
    .face_img_main img{
        width: 100%;
        height: 100%;
    }
    .poiont_div{
        position: absolute;
        top: 0;
        left: 0;
    }
    .poiont_div img{
        width: 19px;
        height: 32px;
    }

    .poiont_div_view{
        position: absolute;
        top: 0;
        left: 0;
    }
    .poiont_div_view img{
        width: 19px;
        height: 32px;
    }
</style>